<template>
  <view>
    <view class="top">
      <BaseNavbar :title="title" />

      <BaseSearch typeImg="screen" placeholder="请输入订单编号/支付单号" @search="search" @onClickIcon="onClickIcon" />

    </view>

    <BaseDropdown :options-list="optionsList" :num="orderTotal" @change="changeDropdown"></BaseDropdown>
    <view class="subsection" @click="handleSubsection">
      <u-subsection mode="subsection" :active-color="mainColor" :list="subsectionList" :current="current"
        @change="changeSubsection" />
      <u-calendar v-model="showCalendar" mode="range" :safe-area-inset-bottom="true" btn-type="error"
        :range-color="mainColor" :active-bg-color="mainColor" :change-year="false" @change="changeCalendar">
      </u-calendar>
    </view>

    <ComList :loading-type="loadingType">

      <OrderListCard @refresh="refresht" v-for="(item, i) in listData" :key="item.order_id" @onCard="card(i)"
        @retunOrder="retunOrder(item)" @onOff="onOff(item)" @start="start" :info="item" />

    </ComList>
    <BasePopup :show.sync="isShowPopup" mode="top" :customStyle="{
      top: 110 + vStatusBarHeight + vNavBarHeight + 'rpx',
    }">
      <OrderScreener @confirm="confirmQuery" />
    </BasePopup>
    <BaseModal :show.sync="isShowDelModalFree" @confirm="confirmDelReturn" title="温馨提示">
      <view class="red">
        确认要退款给该用户吗，退款后将无法追回
      </view>
      <view class="flexBottom">
        <u-radio-group v-model="value" @change="radioGroupChange">
          <u-radio @change="radioChange" v-for="(item, index) in list" :key="index" :name="item.name"
            :disabled="item.disabled">
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </view>
    </BaseModal>
    <BaseModal :show.sync="isShowStartModal" @confirm="confirmStart">
      <view slot="default">
        <BaseInput v-model="length_time" placeholder="请输入启动时长(分钟)" />
      </view>
    </BaseModal>
    <disableBaseModal :show="isShowDelModalOff" @confirmDelOff="confirmDelOff" @cancel="cancel" :index="index">
    </disableBaseModal>
  </view>
</template>

<script>
import BaseNavbar from "@/components/base/BaseNavbar.vue";
import BaseSearch from "@/components/base/BaseSearch.vue";
import BaseDropdown from "@/components/base/BaseDropdown.vue";
import ComList from "@/components/list/ComList.vue";
import OrderListCard from "@/pagesB/components/cards/OrderListCard.vue";
import myPull from "@/mixins/myPull.js";
import BasePopup from "@/components/base/BasePopup.vue";
import OrderScreener from "./components/OrderScreener.vue";
import BaseModal from "@/components/base/BaseModal.vue";
import disableBaseModal from '@/components/disable/disableBaseModal';
import BaseInput from "@/components/base/BaseInput.vue";
import { subtractDaysAndFormat } from "@/wxutil/times";
export default {
  components: {
    BaseNavbar,
    BaseSearch,
    BaseDropdown,
    ComList,
    OrderListCard,
    BasePopup,
    OrderScreener,
    BaseModal,
    disableBaseModal,
    BaseInput
  },
  data() {
    return {
      title: "订单管理",
      optionsList: [
        {
          title: "全部",
          options: [
            { label: "全部", value: 0, status: 0 },
            {
              label: "订单完成",
              value: 1,
              status: 1,
            },
            {
              label: "订单异常",
              value: 2,
              status: 2,
            },
            {
              label: "订单取消",
              value: 3,
              status: 3,
            },
            {
              label: "已退款",
              value: 4,
              status: 50,
            },
            {
              label: "待付款",
              value: 5,
              status: 4,
            },
          ],
          value: 0,
        },
      ],
      dianwei: "",
      device_sn: "",
      order_sn: "",
      order_status: 0,
      room_num: "",
      start_time: "",
      end_time: "",
      orderTotal: 0, //订单总数
      //popup显示状态
      isShowPopup: false,
      selectItem: {},
      isShowDelModalFree: false,
      list: [
        {
          name: '原路返回',
          disabled: false
        },
        {
          name: '线下退款',
          disabled: false
        }
      ],
      value: '原路返回',
      subsectionList: [
        //     {
        //     name: '昨天'
        // },
        {
          name: '今天',
          status: 1,
        },
        {
          name: '昨天',
          status: 2,
        },

        {
          name: '前天',
          status: 3,
        },
        {
          name: '本月',
          status: 4,
        },


        {
          name: '上月',
          status: 5,
        },
        {
          name: '自定义',
          isCustom: true
        }

      ],
      current: 0,
      showCalendar: false,
      mainColor: '#fa3534',
      unBindItem: {},
      list: [
        {
          name: '原路返回',
          disabled: false
        },
        {
          name: '线下退款',
          disabled: false
        }
      ],
      value: '原路返回',
      isShowDelModalFree: false,
      isShowDelModalOff: false,
      isShowStartModal: false,//启动
      index: 4,
      selectIndex: 0,
      length_time: 1,
    };
  },
  methods: {
    cancel() {
      console.log('点击取消')
      this.isShowDelModalOff = false
    },
    /* 禁用设备 */
    onOff(item) {
      if (item.use_status == 1) {
        this.index = 4;
      } else if (item.use_status == 2) {
        this.index = 5
      }
      this.isShowDelModalOff = true
      this.device_sn = item.device_sn
      console.log('禁用启动了', this.device_sn)
      this.unBindItem = item

    },
    /* 禁用设备弹窗 */
    async confirmDelOff(text) {
      this.isShowDelModalOff = false
      console.log('确认信息', text)
      let use_status = 0;
      if (this.index == 4) {
        use_status = 2;

      } else if (this.index == 5) {
        use_status = 1;
      }
      let title = ''
      if (use_status == 2) {
        title = text

      }
      let params = {
        device_sn: this.device_sn,
        use_status,
        reason: title
      };
      this.$u.api
        .setupdateMachineStatus(params).then((res) => {
          console.log("成功返回信息", res);
          // this.refresh();
          let index = this.listData.findIndex((items) => items.order_id === this.unBindItem.order_id); // 查找id为2的元素索引
          if (index !== -1) {
            // 如果找到了
            if (this.unBindItem.use_status == 1) {
              this.unBindItem.use_status = 2
              this.unBindItem.reason = title

            } else if (this.unBindItem.use_status == 2) {
              this.unBindItem.use_status = 1
              this.unBindItem.reason = title

            }
            console.log('找到相同的', this.listData[index], this.unBindItem.use_status)
            this.listData.splice(index, 1, this.unBindItem);
          }
        })
        .catch((err) => {
          console.log("成功返回信息", err);
        });

    },
    start(i, item) {

      // 补货管理才能有启动
      this.selectIndex = i;
      this.isShowStartModal = true;
      console.log("启动设备结果参数 1 ：", i);
      this.unBindItem = item
    },
    confirmStart() {
      // 开启游戏设备
      this.startGameDevice(this.selectIndex + 1, this.length_time);
    },
    startGameDevice(channel, time) {
      // 启动设备
      // 启动设备

      let data = {
        device_sn: this.unBindItem.device_sn,
        channel: channel, // 货道
        length_time: time,
      };
      console.log("启动设备结果参数 3 ：", data);
      this.$u.api.startUM(data).then((res) => {
        console.log("启动设备结果4 ：", res);
        this.isShowSuccess("操作成功", 1, () => { }, true);
      });
    },
    handleSubsection() {
      if (this.current === 5 && !this.showCalendar) this.showCalendar = true
    },
    changeCalendar(e) {
      let { startDate, endDate } = e;
      this.handleData('', startDate, endDate);
    },
    handleData(date, startDate, endDate) {
      // this.queryDate = date
      this.start_time = startDate;
      this.end_time = endDate;
      this.refresh()
    },
    changeSubsection(i) {
      this.current = i
      let selectItem = this.subsectionList[i]
      if (selectItem.isCustom) {
        this.showCalendar = true
      } else {
        let date = new Date()
        if (selectItem.status < 4) {
          this.end_time =  this.start_time = subtractDaysAndFormat(selectItem.status - 1)
        } else if (selectItem.status == 4) {
          this.end_time = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate())
          this.start_time  = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + 1
        } else if (selectItem.status == 5) {
          this.start_time  = date.getFullYear() + '-' + (date.getMonth()) + '-' + 1
          let tiem = new Date(date.getFullYear(), date.getMonth(), 0).getDate()
          this.end_time= date.getFullYear() + '-' + (date.getMonth()) + '-' + tiem
        }

        console.log('结束时间', this.start_time , this.end_time, i, selectItem); //当前日期的年 2022
        this.handleData('', this.start_time, this.end_time)
      }
    },
    radioChange(e) {
      // console.log(e);
    },
    // 选中任一radio时，由radio-group触发
    radioGroupChange(e) {
      // console.log(e);
    },
    confirmDelReturn() {

      let data = {
        order_id: this.unBindItem.order_id,
        money: this.unBindItem.order_amount
        // money:'0.01'
      }
      if (this.value == '线下退款') {
        data['refund_type'] = 1
      } else {
        data['refund_type'] = 0
      }
      console.log('退款提交信息', data)
      this.$u.api.refundOrder(data).then((res) => {
        this.isShowSuccess("执行成功");
        this.refresht()

      })
        .catch((err) => {
          console.log('退款提交失败', err)
        })
    },


    retunOrder(item) {
      this.value = '原路返回'
      this.isShowDelModalFree = true
      this.unBindItem = item
    },

    refresht() {
      setTimeout(() => {

        this.refresh()
      }, 2500);
    },

    search(val) {
      this.order_sn = val;
      this.refresh();
    },
    changeDropdown(item) {
      this.optionsList = item;

      this.order_status = item[0].options[item[0].value].status;
      this.refresh();
    },
    getList(page, done) {
      let data = {
        dianwei: this.dianwei,
        device_sn: this.device_sn,
        room_num: this.room_num,
        start_time: this.start_time,
        end_time: this.end_time,
        order_sn: this.order_sn,
        order_status: this.order_status,
        page,
      };
      this.$u.api.getOrderList(data).then((res) => {
        if(page==1){
          this.orderTotal = res.total.Total;
        }
        done(res.data);
      });
    },
    //点击搜索框右边的icon图标
    onClickIcon(e) {
      if (e == 0) {
        this.isShowPopup = !this.isShowPopup;
      }
    },
    //筛选确认查询
    confirmQuery(data) {
      console.log("🚀 ~ 筛选 data ", data);
      this.dianwei = data.dianwei;
      this.device_sn = data.device_sn;
      this.start_time = data.start_time;
      this.end_time = data.end_time;
      this.order_sn = data.order_sn;
      this.isShowPopup = false;
      this.refresh();
    },
    /* 订单维护 */
    card(i) {
      console.log('订单维护启动', this.listData[i])
      let item = this.listData[i]
      // uni.navigateTo({ url: `/pagesB/order/OrderMaintain?from=''&order_sn=${this.listData[i].order_sn}` });

    }
  },
  onLoad() {

    // setTimeout(() => {

    //   this.refresh();
    // }, 1000);
    this.end_time =  this.start_time =subtractDaysAndFormat(0)
   
   this.handleData('', this.start_time, this.end_time);
   if(this.vInputDisable){
      this.length_time=this.vTime
    }
  
  },
  onShow(e) {
   

    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1]; // 当前页
    if (currPage.data.isDoRefresh == true) {
      // 是否刷新
      currPage.data.isDoRefresh = false;
      this.refresh();
    }
  },
  mixins: [myPull()],
};
</script>
<style lang="scss">
page {
  background-color: $pageBgColor;
}
</style>
<style lang="scss" scoped>
.top {
  position: relative;
  z-index: 999;
}

.subsection {
  background-color: #fff;
  padding: 20rpx;
}

.red {
  text-align: center;
  color: orangered;
  font-size: 22rpx;
}

.flexBottom {

  padding: 3rpx 0;
  display: flex;
  justify-content: center;
  // border: 1px solid #000;
  padding-bottom: 10rpx;
}
</style>
